#include "NeuronDataReaderTypes.h"
#include "NeuronDataReader/NeuronDataReader.h"

/////////////////// Begin FSimpleNeuronDataSource /////////////////////

INeuronDataDispatchAbility::FOnNeuronFrame& FSimpleNeuronDataSource::OnNeuronFrameArrived()
{
	return Dispatcher->OnNeuronFrameArrived( );
}

void FSimpleNeuronDataSource::Dispatch(BvhDataHeader* Header, float* Data)
{
	Dispatcher->Dispatch( Header, Data );
}

void FSimpleNeuronDataSource::SetConfig( TSharedPtr<INeuronNetConfigBaseAbility> Config )
{
	InternalConfig = Config;
}

TSharedPtr<INeuronNetConfigBaseAbility> FSimpleNeuronDataSource::GetConfig( )
{
	return InternalConfig;
}

ConnectionStatus FSimpleNeuronDataSource::GetStatus()
{
	if (SocketInternal)
	{
		return BRGetSocketStatus( SocketInternal );
	}
	else
	{
		return CS_OffWork;
	}
}

void*& FSimpleNeuronDataSource::GetConnectionSocket()
{
	return SocketInternal;
}

bool FSimpleNeuronDataSource::Setup()
{
	if (InternalConfig)
	{
		if (InternalConfig->IsTcpConfig( ))
		{
			TSharedPtr<INeuronTcpConfigAbility> TcpConfig = StaticCastSharedPtr<INeuronTcpConfigAbility>( InternalConfig );
			if (TcpConfig)
			{
				FIPv4Endpoint RemoteEndpoint = TcpConfig->GetRemoteEndpoint( );
				SocketInternal = BRConnectTo(
					TCHAR_TO_ANSI( *RemoteEndpoint.Address.ToString( ) ),
					RemoteEndpoint.Port
					);
			}
		}
		else
		{
			TSharedPtr<INeuronUdpConfigAbility> UdpConfig = StaticCastSharedPtr<INeuronUdpConfigAbility>( InternalConfig );
			if (UdpConfig)
			{
				SocketInternal = BRStartUDPServiceAt( UdpConfig->GetPort( ) );
			}
		}
	}
	
	return (SocketInternal != nullptr);
}

void FSimpleNeuronDataSource::Cutoff()
{
	if (SocketInternal)
	{
		BRCloseSocket( SocketInternal );
	}
}


/////////////////// End FSimpleNeuronDataSource /////////////////////
